from django.core.exceptions import ValidationError
from django.db import IntegrityError
from rest_framework import serializers
from rest_framework.generics import get_object_or_404

from apps.gzde.models import Attachment
from apps.personal_center.models import *
from extensions.serializers import *

class Personal_Center_RegionSerializer(BaseSerializer):
    region_children = SerializerMethodField(read_only=True, label='子类')

    class Meta:
        model = Personal_Center_Region
        fields = '__all__'  # 或者指定需要的字段列表

    def get_region_children(self, obj):
        """获取子类"""
        # 检查是否存在子区域
        if obj.level == 3:
            return None
        if obj.region_children.all().exists():
            # 使用当前序列化器类递归地序列化子区域
            children_serializer = Personal_Center_RegionSerializer(
                obj.region_children.order_by('sort'), many=True)
            return children_serializer.data
        return None


class AddressSerializer(BaseSerializer):

    class Meta:
        model = Address
        read_only_fields = ['id', 'create_time', 'update_time', 'user']
        fields = [
            'name',
            'phone',
            # 'province',
            # 'city',
            # 'district',
            'region',
            'detail',
            'is_default',
            *read_only_fields
        ]

    def create(self, validated_data):
        # 从 validated_data 中获取当前用户
        user = self.context['request'].user
        validated_data['user'] = user

        # 检查用户是否已有地址或是否存在默认地址
        if not Address.objects.filter(user=user).exists() or not Address.objects.filter(user=user, del_flag=False,
                                                                                        is_default=True).exists():
            validated_data['is_default'] = True
        else:
            validated_data['is_default'] = False

        try:
            # 调用父类 create 方法创建新地址对象
            address = super().create(validated_data)

            # 如果新地址是默认地址，确保其他地址不是默认地址
            if address.is_default:
                Address.objects.filter(user=user).exclude(pk=address.pk).update(is_default=False)

            return address

        except IntegrityError as e:
            # 检查错误信息是否与unique_together违规有关
            print('收货地址信息已存在，请勿重复添加。')
            if 'unique constraint' in str(e).lower() or 'must make a unique set' in str(e):
                print('收货地址信息已存在，请勿重复添加。')
                raise ValidationError({
                    'non_field_errors': [
                        '收货地址信息已存在，请勿重复添加。'
                    ]
                })
            else:
                raise e


class Order_ScenePhotosTempSerializer(BaseSerializer):
    class Meta:
        model = Order_ScenePhoto_temp
        read_only_fields = ['id']
        fields = ['file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        return super().create(validated_data)


class Order_ScenePhotosSerializer(BaseSerializer):
    class Meta:
        model = Order_ScenePhoto
        read_only_fields = ['id','name','create_time']
        fields = ['order','file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        return super().create(validated_data)


class OrdersSerializer(BaseSerializer):
    orderPhotos=Order_ScenePhotosTempSerializer(source='Order_ScenePhoto', many=True, read_only=True, label='现场照片')
    order_status_name = SerializerMethodField(read_only=True, label='订单状态')
    # 商品数量
    goods_count = SerializerMethodField(read_only=True, label='商品数量')

    class GoodsSerializer(BaseSerializer):

        class ImageSerializer(BaseSerializer):
            src = CharField(read_only=True, label='资源地址')
            alt = CharField(read_only=True, label='提示')

            class Meta:
                model = Attachment
                fields = ['id', 'src', 'alt', 'name', 'type', 'file']

        images_items = ImageSerializer(source='images', many=True, read_only=True, label='商品图片')

        class Meta:
            model = Goods
            fields = ['id','name','images_items']

    goods_items = GoodsSerializer(source='goods', many=True, read_only=True, label='商品')

    class AddressSerializer(BaseSerializer):

        class Meta:
            model = Address
            fields = "__all__"

    address_detail = AddressSerializer(source='address',read_only=True, label='收货地址')


    class Meta:
        model = Order
        read_only_fields = ['id','order_no','orderPhotos', 'goods_count','address_detail',
                            'create_time', 'update_time','order_status_name','goods_items', 'user']
        fields = [
            'order_status',
            'address',
            'demand_desc',
            'goods',
            *read_only_fields
        ]

    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user
        validated_data['order_status'] = 'yiyuyue'
        order = super().create(validated_data)
        # 获取临时图片的 ID 列表
        temp_photo_ids = self.context['request'].data.get('temp_photo_ids', [])
        if not isinstance(temp_photo_ids, list):
            raise serializers.ValidationError("temp_photo_ids must be a list.")

        for temp_photo_id in temp_photo_ids:
            if temp_photo_id:
                # 根据临时图片的 ID 找到相应的图片
                temp_photo = get_object_or_404(Order_ScenePhoto_temp, id=temp_photo_id)

                # 创建一个新的 Opoc_InspectionPhoto，将图片和新的检查记录关联起来
                Order_ScenePhoto.objects.create(
                    order=order,
                    file=temp_photo.file,
                    name=temp_photo.name,
                    # 其他字段
                )
                # 删除临时图片的记录
                temp_photo.delete()
        return order

    def get_order_status_name(self, obj):
        return obj.get_order_status_display()

    def get_goods_count(self, obj):
        # 这里假设`goods`是定义在Order模型上的关系字段，它是与Goods实例相关联的
        # 直接使用该关系字段来计算数量
        return obj.goods.count()


class Order_ScenePhotosSerializer(BaseSerializer):
    class Meta:
        model = Order_ScenePhoto
        read_only_fields = ['id','name','create_time']
        fields = ['order','file', *read_only_fields]

    def create(self, validated_data):
        validated_data['name'] = validated_data['file'].name
        return super().create(validated_data)
    

class Order_EvaluatesSerializer(BaseSerializer):
    order_evaluatePhotos=Order_ScenePhotosTempSerializer(source='Order_EvaluatePhoto', many=True, read_only=True, label='评价照片')
    class Meta:
        model = Order_Evaluate
        read_only_fields = ['id','order_evaluatePhotos','create_time', 'update_time']
        fields = [
            'order',
            'evaluate_content',
            'evaluate_level',
            'del_flag',
            *read_only_fields
        ]

    def create(self, validated_data):

        order_evaluate = super().create(validated_data)
        # 获取对应的订单
        oorder = get_object_or_404(Order, id=self.context['request'].data.get('order'))
        # 将订单状态改为已评价
        oorder.order_status = 'yipingjia'
        oorder.save()
        # 获取临时图片的 ID 列表
        temp_photo_ids = self.context['request'].data.get('temp_photo_ids', [])
        if not isinstance(temp_photo_ids, list):
            raise serializers.ValidationError("temp_photo_ids must be a list.")

        for temp_photo_id in temp_photo_ids:
            if temp_photo_id:
                # 根据临时图片的 ID 找到相应的图片
                temp_photo = get_object_or_404(Order_ScenePhoto_temp, id=temp_photo_id)

                # 创建一个新的 Opoc_InspectionPhoto，将图片和新的检查记录关联起来
                Order_EvaluatePhoto.objects.create(
                    order_evaluate=order_evaluate,
                    file=temp_photo.file,
                    name=temp_photo.name,
                    # 其他字段
                )
                # 删除临时图片的记录
                temp_photo.delete()
        return order_evaluate


class Construction_TeamsSerializer(BaseSerializer):
    construction_teamPhotos=Order_ScenePhotosTempSerializer(source='Construction_TeamPhoto', many=True, read_only=True, label='施工队伍照片')
    class Meta:
        model = Construction_Team
        read_only_fields = ['id','construction_teamPhotos','create_time', 'update_time','create_user','update_user']
        fields = [
            'name',
            'industry',
            'detail',
            'contact',
            'position',
            'contact_phone',
            'contact_address',
            'id_card',
            'construction_team_type',
            'remark',
            'del_flag',
            *read_only_fields
        ]

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        construction_team = super().create(validated_data)
        # 获取临时图片的 ID 列表
        temp_photo_ids = self.context['request'].data.get('temp_photo_ids', [])
        if not isinstance(temp_photo_ids, list):
            raise serializers.ValidationError("temp_photo_ids must be a list.")

        for temp_photo_id in temp_photo_ids:
            if temp_photo_id:
                # 根据临时图片的 ID 找到相应的图片
                temp_photo = get_object_or_404(Order_ScenePhoto_temp, id=temp_photo_id)

                # 创建一个新的 Opoc_InspectionPhoto，将图片和新的检查记录关联起来
                Construction_TeamPhoto.objects.create(
                    construction_team=construction_team,
                    file=temp_photo.file,
                    name=temp_photo.name,
                    # 其他字段
                )
                # 删除临时图片的记录
                temp_photo.delete()
        return construction_team

